package com.codehacker.job.mallservice.controller;

import com.codehacker.job.mallservice.dao.GoodsImageMapper;
import com.codehacker.job.mallservice.dao.GoodsMapper;
import com.codehacker.job.mallservice.dto.ResponseDTO;
import com.codehacker.job.mallservice.entity.Goods;
import com.codehacker.job.mallservice.entity.GoodsExample;
import com.codehacker.job.mallservice.entity.GoodsImageExample;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * GoodsController
 *
 * @author zhuyuwei
 * @date 26/07/2017
 */
@Controller
@RequestMapping("/api/goods")
public class GoodsController {
    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private GoodsImageMapper goodsImageMapper;

    @GetMapping("/search/all")
    @ResponseBody
    public ResponseDTO<Goods> searchAll(@RequestBody Goods goods) {
        ResponseDTO<Goods> result = new ResponseDTO<Goods>();

        result.getMeta().setCode(0);
        return result;
    }

    @GetMapping("")
    @ResponseBody
    public ResponseDTO<Goods> pageSearch(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit) {
        ResponseDTO<Goods> result = new ResponseDTO<Goods>();
        GoodsExample example = new GoodsExample();

        result.getData().getPaginate().setTotal((int) goodsMapper.countByExample(example));
        List<Goods> goods = goodsMapper.selectByExampleWithPaging(example, (page - 1) * limit, limit);
        for (Goods good: goods) {
            GoodsImageExample goodsImageExample = new GoodsImageExample();
            goodsImageExample.createCriteria().andGoodIdEqualTo(good.getId());
            good.setImages(goodsImageMapper.selectByExample(goodsImageExample));
        }
        result.getData().getItems().addAll(goodsMapper.selectByExampleWithPaging(example, (page - 1) * limit, limit));
        result.getData().getPaginate().setNext(page + 1);
        if (CollectionUtils.isEmpty(result.getData().getItems())) {
            result.getData().getPaginate().setHasNext(false);
        } else {
            result.getData().getPaginate().setHasNext(result.getData().getPaginate().getTotal() < (page + 1) * limit ? false : true);
        }
        result.getData().getPaginate().setPerPage(limit);
        result.getMeta().setCode(0);
        return result;
    }

    @GetMapping("/{id}")
    @ResponseBody
    public ResponseDTO<Goods> getDetail(@PathVariable("id") Integer id) {
        ResponseDTO<Goods> result = new ResponseDTO<Goods>();

        result.getData().getItems().add(goodsMapper.selectByPrimaryKey(id));
        result.getMeta().setCode(0);
        return result;
    }
}
